<template>
  <div class="home">
    <van-nav-bar>
      <template #left>
        <div class="logo"></div>
      </template>
      <template #right>
        <van-button
          class="search-btn"
          round
          icon="search"
          @click="$router.push('/search')"
          >搜索</van-button
        >
      </template>
    </van-nav-bar>
    <van-tabs v-model="active">
      <van-tab v-for="item in ownList" :key="item.id" :title="item.name">
        <article-list :channel_id="item.id" />
      </van-tab>
      <div class="icon-box" @click="show = true">
        <van-icon name="wap-nav" />
      </div>
    </van-tabs>
    <!-- 频道管理 -->
    <van-action-sheet v-model="show" title="频道管理">
      <channel
        :chanList="ownList"
        :channels="channels"
        v-model="active"
        @close="show = false"
      />
    </van-action-sheet>
  </div>
</template>

<script>
import articleList from "./articleList.vue";
import { ownChannelsAPI, channelsAPI } from "@/api";
import Channel from "./channel.vue";
import {getChannel} from '@/utils/storage'
export default {
  components: {
    articleList,
    Channel,
  },
  data() {
    return {
      active: 0,
      show: false,
      // ownList是用户自己的频道
      ownList: [],
      // channels是所有频道
      channels: [],
    };
  },
  async created() {
    let res = await ownChannelsAPI();
    this.ownList = res.data.data.channels;
    let res2 = await channelsAPI();
    this.channels = res2.data.data.channels;
    // 数据持久化
    // 1.先判断用户有没有登录
    // 有登录直接发请求拿到用户频道的数据
    // 并把请求回来的新数据覆盖原来频道的数据
    // 2.要是没有登录
    // 没有登录先判断有没有本地存储
    // 有直接从封装的数据里面拿取数据赋值给用户频道
    // 没有本地存储
    // 在发请求获取数据
    // if(this.$store.state.tokenObj.token){
    //   let res=await ownChannelsAPI();
    //   this.ownList=res.data.data.channels
    // }else{
    //   let res=getChannel()
    //   if(res){
    //     this.ownList=res
    //   }else{
    //     let res=await ownChannelsAPI()
    //     this.ownList=res.data.data.channels
    //   }
    // }

    // 优化
      let local=getChannel()
      // 没有登录或本地存储没有数据的时候发请求获取频道
    if(this.$store.state.tokenObj.token||!local){
        let res=await ownChannelsAPI()
        this.ownList=res.data.data.channels
    }else{
      // 本地存储有数据直接去本地存储的数据
      let res=getChannel()
    }
  },
};
</script>

<style lang="less" scope>
.home {
  .logo {
    width: 130px;
    height: 100%;
    background: url(@/assets/logo.png) no-repeat center/contain;
  }
  .search-btn {
    width: 90px;
    height: 28px;
    background-color: rgba(255, 255, 255, 0.2);
    border: none;
    color: #fff;
    .van-icon {
      color: #fff;
    }
  }
  .van-tabs {
    position: relative;

    .van-tabs__wrap {
      width: 345px;
    }

    .icon-box {
      position: absolute;
      right: 0;
      top: 7px;
      width: 30px;
      height: 44px;
      .van-icon-wap-nav {
        font-size: 28px;
      }
    }
  }
}
</style>